﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VSSTQH.DataAccess;

namespace VSSTQH
{
    public partial class FrmUpdateVendor : Form
    {
        #region Ctors
        public FrmUpdateVendor()
        {
            InitializeComponent();

            Initialize();

        }
        #endregion

        #region Singleton Members
        //private static volatile FrmUpdateVendors instance;
        //private static object syncRoot = new Object();

        ///// <summary>
        ///// Create Instance
        ///// </summary>
        //public static FrmUpdateVendors Instance
        //{
        //    get
        //    {
        //        lock (syncRoot)
        //        {
        //            if (instance == null)
        //                instance = new FrmUpdateVendors();
        //        }

        //        return instance;
        //    }
        //}

        ///// <summary>
        ///// Free Instance
        ///// </summary>
        ///// <param name="e"></param>
        //protected override void OnClosed(EventArgs e)
        //{
        //    //instance = null;
        //    base.OnClosed(e);
        //}

        #endregion

        #region Field Members
        private bool _isEdit = false;
        private bool _isBinding = false;
        private IVendorDAO _dataAccess = new VendorDAO();
        #endregion

        #region Property Members
        private VendorModel _vendor = new VendorModel();
        public VendorModel Vendor
        {
            get { return _vendor; }
            set
            {
                if (_vendor != value)
                {
                    _isEdit = true;
                    _vendor = value;
                }
            }
        }

        private IList<VendorModel> _collection;
        public IList<VendorModel> Collection
        {
            set { _collection = value; }
        }
        #endregion

        #region Methods

        private void Initialize()
        {
            this.MaximizeBox = false;

            this.Load += new EventHandler(delegate
            {
                BindingControls();
                ValidatingControls();

                this.edtVendorID.Enabled = !_isEdit;
            });
            this.btnSave.Click += new EventHandler(delegate { ClickButtonSave(); });
            this.btnClose.Click += new EventHandler(delegate { this.Close(); });
        }

        protected override void OnLoad(EventArgs e)
        {
            if (_isEdit)
                this.edtVendorID.Enabled = false;
            base.OnLoad(e);
        }

        private void ResetBindingControls()
        {
            this.edtVendorID.DataBindings.Clear();
            this.edtVendorName.DataBindings.Clear();
            this.edtTelephone.DataBindings.Clear();
            this.edtFax.DataBindings.Clear();
            this.edtTaxID.DataBindings.Clear();
            this.edtAddress.DataBindings.Clear();
            this.edtDescription.DataBindings.Clear();
            this._isBinding = false;
        }
        private void BindingControls()
        {
            if (!_isBinding)
            {
                this.edtVendorID.DataBindings.Add("Text", Vendor, "VendorID");
                this.edtVendorName.DataBindings.Add("Text", Vendor, "VendorName");
                this.edtTelephone.DataBindings.Add("Text", Vendor, "Telephone");
                this.edtFax.DataBindings.Add("Text", Vendor, "Fax");
                this.edtTaxID.DataBindings.Add("Text", Vendor, "TaxID");
                this.edtAddress.DataBindings.Add("Text", Vendor, "Address");
                this.edtDescription.DataBindings.Add("Text", Vendor, "Description");
                _isBinding = true;
            }
        }
        private void ValidatingControls()
        {
            string errorMessage = String.Empty;
            this.edtVendorName.Validating += new CancelEventHandler(delegate
            {
                errorMessage = String.IsNullOrEmpty(this.edtVendorName.Text) ?
                    "Họ tên phải được nhập" : String.Empty;
                errorProvider.SetError(this.edtVendorName, errorMessage);
            });

            this.edtAddress.Validating += new CancelEventHandler(delegate
            {
                errorMessage = String.IsNullOrEmpty(this.edtAddress.Text) ?
                    "Địa chỉ phải được nhập" : String.Empty;
                errorProvider.SetError(this.edtAddress, errorMessage);
            });

            this.edtTelephone.KeyPress += new KeyPressEventHandler(edtTelephone_KeyPress);
        }

        void edtTelephone_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) &&
                e.KeyChar != Convert.ToChar(Keys.Back) &&
                e.KeyChar != '-')
            {
                e.Handled = true;
            }
        }

        #endregion

        #region Action Members

        /// <summary>
        /// Click button save
        /// </summary>
        private void ClickButtonSave()
        {
            bool invalidInput = false;

            foreach (Control ctrl in this.Controls)
            {
                if (errorProvider.GetError(ctrl) != String.Empty)
                {
                    invalidInput = true;
                    break;
                }
            }

            if (invalidInput)
            {
                Common.ShowAlert("Thông tin bạn nhập chưa hợp lệ, vui lòng kiểm tra lại");
            }
            else
            {
                this.errorProvider.Clear();

                _vendor.ModifiedByID = Common.UserLogin.Username;
                _vendor.ModifiedDate = DateTime.Now;

                bool result = false;
                if (!_isEdit)
                {
                    _vendor.CreatedByID = Common.UserLogin.Username;
                    _vendor.CreationDate = DateTime.Now;
                    result = _dataAccess.Add(_vendor);

                    if (result)
                    {
                        _collection.Add(_vendor);
                        _vendor = new VendorModel() { Active = true };
                        ResetBindingControls();
                        BindingControls();
                        this.edtVendorID.Focus();

                    }
                    else
                    {
                        Common.ShowAlert("Tạo mới thông tin khách hàng không thành công.");
                    }
                }
                else
                {
                    result = _dataAccess.Edit(_vendor);

                    if (result)
                    {
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        Common.ShowAlert("Chỉnh sửa thông tin khách hàng không thành công.");
                    }


                }
            }
        }

        #endregion

    }
}
